// NanNan.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"
#include <tchar.h>
#include <commctrl.h>
#include "SpacePortal.h"
#include "Win32Tool.h"

#pragma comment(lib, "comctl32.lib")

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

    HANDLE  MutexOneInstance = ::CreateMutex( NULL, FALSE,
	  _T("SPACEPORTAL0.0.1_CREATED_BY_ZHANGHONGBING"));

    bool AlreadyRunning = ( ::GetLastError() == ERROR_ALREADY_EXISTS || 
                       ::GetLastError() == ERROR_ACCESS_DENIED);
    // The call fails with ERROR_ACCESS_DENIED if the Mutex was 
    // created in a different users session because of passing
    // NULL for the SECURITY_ATTRIBUTES on Mutex creation);

    if ( AlreadyRunning )return 0;
	
	INITCOMMONCONTROLSEX ics;
	ics.dwSize = sizeof(INITCOMMONCONTROLSEX);
	ics.dwICC  = ICC_INTERNET_CLASSES;
    InitCommonControlsEx(&ics);
	
	CSpacePortal Portal;

	
	SetThreadName(-1,"MainThread");
     
	CWinSpace2::RegisterCommonClass(hInstance);

	RECT rc;
	::SetRect(&rc,0,0,300,200);
	if(!Portal.Create(hInstance,"World",WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,rc,NULL)){
		int n = ::GetLastError();
		return 0;
	}


	HICON hIcon = ::LoadIcon(hInstance,MAKEINTRESOURCE(IDI_MYWORLD));
    
	assert(hIcon != NULL);
	::SendMessage(Portal.GetHwnd(), WM_SETICON, TRUE, (LPARAM)hIcon);
	::SendMessage(Portal.GetHwnd(), WM_SETICON, FALSE, (LPARAM)hIcon);

	Portal.SetIcon(hIcon);
    Portal.SetTitle("SpacePortal 1.0.0.0");

	CenterWindow(Portal.GetHwnd(),NULL);
	::ShowWindow(Portal.GetHwnd(), SW_SHOW);
    ::UpdateWindow(Portal.GetHwnd());

	if(!Portal.InitSocket()){
		PostQuitMessage(0);		
	}
	else if(!Portal.Activation()){
	    PostQuitMessage(0);
	}

	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	
    Portal.Dead();

	if(MutexOneInstance)CloseHandle(MutexOneInstance);

	return 0;
}



